<template>
	<view class="chat-container">
		<!-- 顶部标题 -->
		<view class="chat-header">
			管理员: {{ adminName }}
		</view>

		<!-- 聊天内容区域 -->
		<scroll-view class="chat-content" :scroll-y="true">
			<view v-for="(message, index) in messages" :key="index"
				:class="['chat-item', message.isUser ? 'self' : 'other']">
				<!-- 用户头像和消息框 -->
				<image v-if="!message.isUser" class="avatar" src="http://localhost:8007/img/get?url=对方.png" />
				<view class="message-box">
					<text class="message-content">{{ message.content }}</text>
				</view>
				<!-- 用户头像在右边 -->
				<image v-if="message.isUser" class="avatar" src="http://localhost:8007/img/get?url=己方.png" />
			</view>
		</scroll-view>

		<!-- 底部输入框 -->
		<view class="chat-footer">
			<input class="input-message" type="text" placeholder="请输入消息..." v-model="message" />
			<button class="send-button" @click="sendMessage">发送</button>
		</view>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				adminName: "", // 动态获取的管理员名称
				messages: [], // 聊天记录（从缓存中加载）
				message: "", // 当前输入的消息
				ws: null // WebSocket 连接实例
			};
		},
		methods: {
			// 获取管理员名称
			fetchAdminName() {
				uni.request({
					url: "http://localhost:8006/user/getAdminName?adminId=1",
					method: "GET",
					success: (res) => {
						if (res.data && res.data.data) {
							this.adminName = res.data.data;
							console.log(this.adminName);
						}
					},
					fail: (err) => {
						console.error("获取管理员名称失败", err);
					}
				});
			},

			// 连接 WebSocket
			connectWebSocket() {
				if (this.ws) {
					uni.closeSocket(); // 如果已有连接，关闭它
				}

				const wsUrl =
					`ws://localhost:8006/ws?userId=user${this.$store.state.userInfo.userId}`; // 用户ID为123，实际替换为动态值
				uni.connectSocket({
					url: wsUrl
				});

				uni.onSocketOpen(() => {
					console.log("WebSocket 连接成功");
					uni.showToast({
						title: "WebSocket 连接成功",
						icon: "success"
					});
				});

				uni.onSocketMessage((event) => {
					const receivedData = JSON.parse(event.data); // 解析接收到的消息
					console.log("接收到消息:", receivedData);
					let newMessage = {
						from: receivedData.from, // 替换为当前用户ID
						to: `user${this.$store.state.userInfo.userId}`,
						content: receivedData.message,
						isUser: false,
						time: receivedData.time
					}
					// 添加到消息记录
					if (newMessage.from === 'admin1') {
						this.addMessage(newMessage);
					}
					this.updateCache(newMessage);
				});

				uni.onSocketClose(() => {
					console.log("WebSocket 连接已关闭");
					uni.showToast({
						title: "WebSocket 已关闭",
						icon: "none"
					});
				});

				uni.onSocketError((err) => {
					console.error("WebSocket 出现错误:", err);
					uni.showToast({
						title: "WebSocket 错误",
						icon: "none"
					});
				});
			},


			// 发送消息
			sendMessage() {
				if (!this.message.trim()) {
					uni.showToast({
						title: "请输入内容",
						icon: "none"
					});
					return;
				}

				const newMessage = {
					from: `user${this.$store.state.userInfo.userId}`, // 替换为当前用户ID
					to: "admin1",
					content: this.message,
					isUser: true,
					time: new Date().toISOString()
				};

				// 添加到本地消息记录
				this.addMessage(newMessage);
				this.updateCache(newMessage);
				// 模拟发送消息到后端
				uni.request({
					url: `http://localhost:8006/chat/send`,
					method: "GET",
					data: {
						from: `user${this.$store.state.userInfo.userId}`, // 替换为当前用户ID
						to: "admin1",
						content: this.message
					},
					success: (res) => {
						console.log("消息发送成功:", res.data);
						uni.showToast({
							title: "消息发送成功",
							icon: "success"
						});
					},
					fail: (err) => {
						console.error("消息发送失败:", err);
						uni.showToast({
							title: "消息发送失败",
							icon: "none"
						});
					}
				});

				this.message = ""; // 清空输入框
			},

			// 添加消息记录并存储到缓存
			// 添加消息记录并存储到缓存
			addMessage(newMessage) {
				const lastMessage = this.messages[this.messages.length - 1];

				// 检查是否需要插入时间分割
				if (
					lastMessage &&
					new Date(newMessage.time) - new Date(lastMessage.time) > 5 * 60 * 1000
				) {
					this.messages.push({
						content: newMessage.time,
						isTimeDivider: true
					});
				}

				this.messages.push(newMessage);
			},
			updateCache(newMessage) {
				// 获取当前缓存中的消息
				const cachedMessages = uni.getStorageSync("chatMessages") || [];

				// 将新消息添加到缓存
				cachedMessages.push(newMessage);

				// 更新缓存
				uni.setStorageSync("chatMessages", cachedMessages);
			},

			// 加载缓存中的消息记录
			loadMessages() {
				const cachedMessages = uni.getStorageSync("chatMessages") || [];

				// 只加载当前用户相关的消息
				this.messages = cachedMessages.filter(
					(msg) =>
					(msg.from === `user${this.$store.state.userInfo.userId}` && msg.to === "admin1") ||
					(msg.from === "admin1" && msg.to === `user${this.$store.state.userInfo.userId}`)
				);
			}

		},
		mounted() {
			this.fetchAdminName(); // 获取管理员名称
			this.loadMessages(); // 加载历史消息
			this.connectWebSocket(); // 连接 WebSocket
		},
		onLoad() {
			this.connectWebSocket(); // 连接 WebSocket
			this.fetchAdminName(); // 获取管理员名称
			this.loadMessages(); // 加载历史消息

		},
		beforeDestroy() {
			uni.closeSocket(); // 如果已有连接，关闭它
		}
	};
</script>

<style>
	.chat-container {
		display: flex;
		flex-direction: column;
		height: 100vh;
		background-color: #f4f4f4;
	}

	.chat-header {
		height: 50px;
		line-height: 50px;
		text-align: center;
		font-size: 16px;
		font-weight: bold;
		background-color: #fff;
		border-bottom: 1px solid #ddd;
	}

	.chat-content {
		flex: 1;
		padding: 10px;
		background-color: #f4f4f4;
		overflow-y: auto;
	}

	.chat-item {
		display: flex;
		align-items: flex-start;
		margin-bottom: 5%;
		/* 消息之间的间隔 */
		width: 100%;
		/* 保证整体宽度为100% */
	}

	.chat-item.self {
		justify-content: flex-end;
		/* 用户消息靠右 */
	}

	.chat-item.other {
		justify-content: flex-start;
		/* 对方消息靠左 */
	}

	.avatar {
		width: 10vw;
		/* 头像宽度为屏幕的15% */
		height: 10vw;
		border-radius: 50%;
		/* 圆形头像 */
		margin: 0 5%;
		/* 距离屏幕边缘5% */
	}

	.message-box {
		max-width: 60%;
		/* 消息宽度为屏幕的60% */
		padding: 10px;
		/* 内边距 */
		border-radius: 10px;
		/* 圆角 */
		background-color: #fff;
		/* 背景色 */
		position: relative;
		box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
		/* 阴影 */
		box-sizing: border-box;
		/* 让 padding 不影响 width */
		word-wrap: break-word;
		/* 长单词换行 */
		overflow-wrap: break-word;
		/* 兼容性换行 */
	}

	.chat-item.self .message-box {
		background-color: #007aff;
		color: #fff;
	}

	.chat-item.self .message-box:after {
		right: -5px;
		/* 调整三角形位置 */
		border-left-color: #007aff;
		/* 三角形颜色 */
	}

	.chat-item.other .message-box:after {
		left: -5px;
		/* 调整三角形位置 */
		border-right-color: #fff;
		/* 三角形颜色 */
	}

	.message-box:after {
		content: '';
		position: absolute;
		top: 10px;
		width: 0;
		height: 0;
		border: 5px solid transparent;
	}

	.message-content {
		font-size: 14px;
		line-height: 20px;
	}

	.chat-footer {
		display: flex;
		align-items: center;
		padding: 10px;
		background-color: #fff;
		border-top: 1px solid #ddd;
	}

	.input-message {
		flex: 1;
		height: 40px;
		padding: 0 10px;
		border: 1px solid #ddd;
		border-radius: 20px;
	}

	.send-button {
		margin-left: 10px;
		padding: 0 20px;
		height: 40px;
		line-height: 40px;
		background-color: #007aff;
		color: #fff;
		border-radius: 20px;
		border: none;
	}
</style>